package main

import (
	"fmt"
	"math/rand"
	"net/http"
	"time"

	"github.com/smira/go-statsd"
)

var client *statsd.Client

func homeHandler(w http.ResponseWriter, r *http.Request) {
	start := time.Now()

	// random sleep
	num := rand.Int31n(100)
	time.Sleep(time.Duration(num) * time.Millisecond)
	fmt.Fprintf(w, "duration: %d", num)

	client.Incr("requests.counter,page=home", 1)
	client.PrecisionTiming("requests.latency,page=home", time.Since(start))
}

func main() {
	// init client
	client = statsd.NewClient("localhost:8125",
		statsd.TagStyle(statsd.TagFormatInfluxDB),
		statsd.MaxPacketSize(1400),
		statsd.MetricPrefix("http."),
		statsd.DefaultTags(statsd.StringTag("service", "n9e-webapi"), statsd.StringTag("region", "bj")),
	)

	defer client.Close()

	http.HandleFunc("/", homeHandler)
	http.ListenAndServe(":8000", nil)
}
